/*
 * @Author: DUST
 * @Date: 2023-06-28 09:25:04
 * @LastEditors: DUST
 * @LastEditTime: 2023-06-29 09:33:50
 * @FilePath: \koa-node-ts\app\controller\WebsiteController.ts
 * @Description: 
 * undefined
 */

import { Context } from "koa";
import validate from "../../utils/validator";
import WebsiteValidator, { WebsiteItem } from "../validator/WebsiteValidator";
import responese from "../../utils/responese";
import WebsiteService from "../service/WebsiteService";
import pagination from "../../utils/pagination";
import NavigateService from "../service/NavigateService";

class WebsiteController {
  async addWebsite(ctx: Context) {
    const { data, msg } = await validate(ctx, WebsiteValidator.addRules);
    if(msg) return responese.errorResponese(ctx, msg);

    const [ rows, created ] = await WebsiteService.addWebsite(data);
    if(!created) return responese.errorResponese(ctx, "该地址的网站已存在");
    if(rows?.id) return responese.success(ctx, null);
    return responese.errorResponese(ctx, "新增失败");
  }

  async getWebsitePage(ctx: Context) {
    const { pageNumber, pageSize } = pagination.getPageParams(ctx);
    
    const { rows, count } = await WebsiteService.getWebsiteList(pageNumber, pageSize);

    const paginationData = pagination.doPaginate(rows, pageSize, count, pageNumber);

    return responese.success(ctx, paginationData);
  }

  async editWebsite(ctx: Context) {
    const { data: { name, url, logoUrl, id, description, type }, msg } = await validate<WebsiteItem & { id: number }>(ctx, WebsiteValidator.addRules);

    if(msg) return responese.errorResponese(ctx, msg);
    if(isNaN(id)) return responese.errorResponese(ctx, "ID参数类型错误");

    const row = await WebsiteService.editWebsite({name, url, logoUrl, description, type}, id);

    if(row) return responese.success(ctx, null);
    return responese.errorResponese(ctx, "编辑失败");
  }

  async deleteWebsite(ctx: Context) {
    const params = ctx.params;
    if(isNaN(params.id)) return responese.errorResponese(ctx, "ID参数类型错误");
    const row = await WebsiteService.deleteWebsite(params.id);

    if(row) return responese.success(ctx, null);
    return responese.errorResponese(ctx, "删除失败")
  }

  async getWebsiteList(ctx: Context) {
    const rows = await NavigateService.getList();
    if(rows) {
      for (let index = 0; index < rows.length; index++) {
        const val: {dataValues: { name: string; id: number, websites?: WebsiteItem[] } } = rows[index];
        val.dataValues.websites = await WebsiteService.getListByType(val.dataValues.id);
      }
      // rows.forEach(async (val: { name: string; id: number, websites?: WebsiteItem[] }) => {
      //   val.websites = await WebsiteService.getListByType(val.id);
      // })
    }
    console.log(rows);
    return responese.success(ctx, rows);
  }
}

export default new WebsiteController;